<template>
	<view class="content">
		<view class="user-infoma">
			<view class="userandday">
				<text class="title">你好，{{name}}</text>
				<view class="day">
					<text>{{ currentDate }}</text>
					<text>{{ currentDay }}</text>
				</view>
			</view>
			<image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar" mode="widthFix">
			</image>
		</view>
		<view class="weathercard">
			<view class="weather-temp">
				<image v-if="dayweather === '多云' " src="../static/images/weather/cloud.png" class="weather-icon">
				</image>
				<image v-else-if="dayweather === '晴' " src="../static/images/weather/sun.png" class="weather-icon">
				</image>
				<image v-else-if="dayweather.includes('雨')" src="../static/images/weather/rain.png" class="weather-icon">
				</image>

				<view class="weather-writing">
					<text class="dayweather"> {{dayweather}}</text>
					<text class="weathercity"> {{weatherpro}}省{{weathercity}}市</text>
				</view>
				<view class="degree">
					<text class="maxdegree">{{maxdegree}}°</text>
				</view>
			</view>
			<view class="weather-temp2">
				<view class="two">
					<text class="two_top">{{aqi}}CN</text>
					<text class="two_botton">空气质量</text>
				</view>
				<view class="two">
					<text class="two_top">{{direction}}</text>
					<text class="two_botton">风向</text>
				</view>
				<view class="two">
					<text class="two_top">{{power}}级</text>
					<text class="two_botton">风力等级</text>
				</view>
			</view>
		</view>
		<view class="List">
			<text class="room">我的房间</text>
			<view class="more" @click="MoreRoom">全部</view>
		</view>
		<view class="RoomAll">
			<view v-for="(room,index) in roomList" :key="index" class=" RoomList">
				<view class="room-switch">
					<image v-bind:src="`../static/images/room/room${room.roomPic}.png` " class="room-icon"></image>
					<image src="/static/images/room/switch.png" class="switch-icon"
						@click="handleSwitchClick(room, index)"></image>
				</view>
				<view class="room-name">{{room.roomName}}</view>
				<view class="device-num">{{getOnlineDeviceCount(room.roomId)}}个设备在线</view>
			</view>

		</view>


		<modal :visible="modalVisible" @close="modalVisible = false" @confirm="handleModalConfirm">
			<view>{{ modalMessage }}</view>
		</modal>
	</view>
</template>

<script>
	import {
		listDevice,
		getDevice,
		addDevice,
		updateDevice,
		delDevice
	} from '@/api/device/device.js';
	import {
		getWeather
	} from '@/api/weather/weather.js'
	import {
		getRoom
	} from '@/api/room/room.js'
	import Modal from "@/components/Modal.vue";

	export default {
		components: {
			Modal // 注册 Modal 组件
		},
		data() {
			return {
				name: this.$store.state.user.name,
				currentDate: '',
				deviceList: [],
				currentDay: '',
				weathercity: '',
				dayweather: '',
				maxdegree: '',
				weatherpro: '',
				aqi: '',
				direction: '',
				power: '',
				roomList: [],
				modalVisible: false,
				modalMessage: '',
				currentRoomIndex: null,
				allLightsOn: false // 初始状态
			}
		},
		computed: {
			avatar() {
				return this.$store.state.user.avatar
			},
			windowHeight() {
				return uni.getSystemInfoSync().windowHeight - 50
			}
		},
		methods: {
			onMoreClicked() {
				// 点击“更多”时执行的代码  
				console.log('更多被点击了');
			},
			MoreRoom() {
				uni.navigateTo({
					url: "/pages/room/room"
				})
			},
			getCurrentDate() {
				const date = new Date();
				const year = date.getFullYear();
				const month = date.getMonth() + 1; // getMonth() returns 0-11
				const day = date.getDate();
				this.currentDate = `${month}月${day}日`;
			},
			getCurrentDay() {
				const date = new Date();
				const days = ['  星期日', '  星期一', '  星期二', '  星期三', '  星期四', '  星期五', '  星期六'];
				const day = date.getDay();
				this.currentDay = days[day];
			},
			handleToAvatar() {
				this.$tab.navigateTo('/pages/mine/avatar/index')
			},
			//读取天气函数
			getWeatherList() {
				getWeather().then(res =>{
					console.log(res);
					this.weathercity = res.data.result.city.city;
				})

				//      const weatherApiUrl = 'https://api.oioweb.cn/api/weather/GetWeather';

				//         axios.get(`${weatherApiUrl}`)
				//             .then(response => {
				//                 console.log(response.data);
				//                 // 处理响应数据
				//                 this.weathercity= response.data;
				//              
				//             })
				//             .catch(error => {
				//                 console.error(error);
				//              
				//             });

				// 天气API的URL
				const weatherApiUrl = 'https://api.oioweb.cn/api/weather/GetWeather';
				fetch(`${weatherApiUrl}`)
					.then(response => response.json())
					.then(data => {
						//	console.log(data);
						//		console.log(data.result.city.City)
						this.weathercity = data.result.city.City
						this.weatherpro = data.result.city.Province
						this.dayweather = data.result.condition.day_weather
						this.maxdegree = data.result.condition.max_degree
						this.aqi = data.result.condition.aqi.aqi
						this.direction = data.result.condition.night_wind_direction
						this.power = data.result.condition.night_wind_power
					})
					.catch(error => {
						console.error(error);
					});
			},
			// getWeatherList() {
			//         const weatherApiUrl = 'https://api.oioweb.cn/api/weather/GetWeather';

			//         uni.request({
			//             url: weatherApiUrl,
			//             method: 'GET',
			//             success: (res) => {
			//                 if (res.statusCode === 200) {
			//                     const data = res.data;
			//                     this.weathercity = data.result.city.City;
			//                     this.weatherpro = data.result.city.Province;
			//                     this.dayweather = data.result.condition.day_weather;
			//                     this.maxdegree = data.result.condition.max_degree;
			//                     this.aqi = data.result.condition.aqi.aqi;
			//                     this.direction = data.result.condition.night_wind_direction;
			//                     this.power = data.result.condition.night_wind_power;
			//                 } else {
			//                     console.error('获取天气信息失败:', res);
			//                 }
			//             },
			//             fail: (err) => {
			//                 console.error('请求失败:', err);
			//             }
			//         });
			//     },
			getRoomList() {
				getRoom(this.userId).then(res => {
					console.log(res.rows);
					this.roomList = res.rows;
					// console.log(this.roomList)
				})
			},
			getDeviceList() {
				getDevice().then(res => {
					//		console.log(res.rows);
					this.deviceList = res.rows;
					console.log(this.deviceList);
				}).catch(error => {
					console.error('Error fetching device:', error);
				});
			},
			getOnlineDeviceCount(roomId) {
				// console.log("11111111111111111111111111111");
				// console.log(this.deviceList.filter(device => device.roomId === roomId && device.status === true).length);
				// return this.deviceList.filter(device => device.roomId === roomId && device.status === true).length;
				 // console.log("当前房间 ID：", roomId);
				 //  console.log("设备列表：", this.deviceList);
				  
				  const onlineDevices = this.deviceList.filter(device => {
					return device.roomId === roomId && device.status === 'true';
				  });
				  
				  // console.log(`Room ID: ${roomId}, 在线设备数量: ${onlineDevices.length}`);
				  return onlineDevices.length;
			},
			handleSwitchClick(room, index) {
				this.currentRoomIndex = index;
				this.modalMessage = '是否关闭所有灯光？';
				this.modalVisible = true;
			},
			handleModalConfirm() {
				// 这里可以处理确定按钮点击后的逻辑
				this.modalVisible = false; // 关闭弹窗
			}
		},
		//页面加载的时候会执行这里的函数
		onShow() {
			console.log("1");
			this.getCurrentDate();
			this.getCurrentDay();
			this.getWeatherList();
			this.getRoomList();
			this.getDeviceList();
		},

	}
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #f9f9f9;
		min-height: 100%;
		height: auto;
	}

	/* #endif */
	.content {
		padding: 40rpx;
		
	}

	.title {
		font-size: 26px;
		color: #4e6490;
		font-weight: bold;
		/* 加粗 */
	}

	.day {
		color: #747474;
		padding-top: 9rpx;
	}

	.user-infoma {
		display: flex;
		justify-content: space-between;
	}

	.userandday {
		display: flex;
		flex-direction: column;
		/* 设置子元素垂直排列 */
		padding: 10rpx;
	}

	.cu-avatar {
		width: 50px;
		border-radius: 50%;
		/* 圆形 */
	}

	.cu-avatar.large {
		width: 30rpx;
		/* 增加图片宽度 */
	}

	.cu-avatar.xl {
		width: 3rpx;
		/* 更大尺寸 */
	}

	.weathercard {
		background: linear-gradient(to bottom, #a18efc, #654bff);
		/* 渐变 */
		margin-top: 25rpx;
		padding: 10rpx;
		height: 55vw;
		border-radius: 45rpx;
		display: flex;
		flex-direction: column;
		/* 设置子元素垂直排列 */
	}

	.weather-temp {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.weather-icon {
		flex: 1.5;
		height: 150rpx;
		width: 15vw;
		margin-top:38rpx;

	}

	.weather-writing {
		flex: 2;
		display: flex;
		flex-direction: column;
		margin-left: 26rpx;
	}

	.degree {
		flex: 1;

	}

	.maxdegree {
		color: white;
		font-size: 40px;
	}

	.weathercity {
		margin-top: 20rpx;
		color: #ced3df;
		font-size: 15px;
	}

	.dayweather {
		margin-top: 15rpx;
		color: white;
		font-size: 18px;
	}

	.weather-temp2 {
		display: flex;
		padding: 55rpx;
	}

	.two {
		flex: 2;
		display: flex;
		flex-direction: column;

	}

	.two_top {
		font-size: 18px;
		color: white;
	}

	.two_botton {
		font-size: 13px;
		color: #ced3df;
		margin-top: 15rpx;
	}

	.List {
		padding: 29rpx;
		display: flex;
		margin-top: 10rpx;
		justify-content: space-between;
		/* 让子元素分别位于容器两端 */
	}

	.room {
		font-size: 20px;
		color: #4e6490;
		font-weight: bold;
		float: left;
	}

	.more {
		color: #654bff;
		float: right;
		font-size: 18px;
	}

	.room-icon {
		height: 98rpx;
		width: 98rpx;
		border-radius: 15%;

	}

	.RoomAll {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		/* 调整间距 */
	}

	.RoomList {
		display: block;
		margin: auto;
		background-color: white;
		padding: 42rpx;
		margin-bottom: 35rpx;
		margin: 10rpx auto;
		border-radius: 30rpx;
		/* 圆角边框 */

		border: 1px #ced3df;
		/* 设置外边框 */
		box-shadow: 0 2rpx 3px rgba(0, 0, 0, 0.1);
		/* 阴影效果 */
		height: 360rpx;
		width: calc(50% - 20rpx);
		/* 每行两个元素，减去边距 */
		box-sizing: border-box;
		/* 包括内边距和边框在内计算宽度 */
	}

	.RoomList:nth-child(2n+1) {
		margin-left: 0;
		/* 确保每行的第一个元素靠左 */
	}

	.RoomList:nth-child(2n) {
		margin-right: 0;
		/* 确保每行的第二个元素靠右 */
	}

	.room-name {
		font-size: 19px;
		color: #4e6490;
		font-weight: bold;
		padding-top: 39rpx;
	}

	.device-num {
		color: #a3a7af;
		margin-top: 19rpx;
		font-size: 14px;
	}

	.room-switch {
		display: flex;
		justify-content: space-between;
	}

	.switch-icon {
		height: 80rpx;
		width: 80rpx;
		margin-top: 15rpx;
	}
</style>